package com.fastjars.business.spring.fastjson;

import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fastjars.business.spring.http.Resp;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

/**
 * FastJsonHttpMessageConverter
 *
 * @author Brant Liu <br> 邮箱：<br>lbf1988@qq.com <br>日期：<br>2018/05/08
 * @version 1.0.0
 */
public class FastJsonHttpMessageConverter extends com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter {

    @Override
    public void write(Object object, Type type, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        if (object instanceof Resp) {
            Resp resp = (Resp) object;
            if (null != resp.getFilters()) {
                addFilter(resp.getFilters());
            } else if (null != resp.getIncludeFeatures()) {
                addFeature(resp.getIncludeFeatures());
            } else if (null != resp.getExcludeFeatures()) {
                removeFeature(resp.getExcludeFeatures());
            }
        }
        super.write(object, type, contentType, outputMessage);
    }

    protected void addSerializerFeature(SerializerFeature feature) {
        if (null == feature) {
            return;
        }
        int length = super.getFastJsonConfig().getSerializerFeatures().length;
        SerializerFeature[] features = new SerializerFeature[length + 1];
        System.arraycopy(super.getFastJsonConfig().getSerializerFeatures(), 0, features, 0, length);
        features[features.length - 1] = feature;
        super.getFastJsonConfig().setSerializerFeatures(features);
    }

    protected void removeSerializerFeature(SerializerFeature feature) {
        if (null == feature) {
            return;
        }
        List<SerializerFeature> features = Arrays.asList(super.getFastJsonConfig().getSerializerFeatures());
        for (int i = 0, len = features.size(); i < len; i++) {
            if(feature.name().equals(features.get(i).name())){
                features.remove(feature);
            }
        }
        super.getFastJsonConfig().setSerializerFeatures((SerializerFeature[]) features.toArray());
    }

    private void addFeature(SerializerFeature[] features) {
        for (SerializerFeature feature : features) {
            addSerializerFeature(feature);
        }
    }

    private void removeFeature(SerializerFeature[] features) {
        for (SerializerFeature feature : features) {
            removeSerializerFeature(feature);
        }
    }

    private void addFilter(SerializeFilter[] filters) {
        for (SerializeFilter filter : filters) {
            super.addSerializeFilter(filter);
        }
    }
}
